<?php
/**
 * Created by PhpStorm.
 * User: 程阳
 * Date: 2017/2/28
 * Time: 19:59
 */

namespace Home\Controller;
use Common\Controller\HomeController;
use Org\Util\Cart;

class ContentController extends HomeController
{
    public function __init(){
        $headConfig = [
            'css' => ['buy-choose.min'],
            'js' => ['buyChoose.min'],
            'title' => '小麦商城',
        ];
        $this->assign('headConfig',$headConfig);
    }

    public function index(){
        $gid = I('get.gid');
        //获取当前商品相关数据
        $goodsData = M('Goods')->alias('g')
            ->join("xm_goods_details d on g.gid=d.gid")
            ->where("g.gid=$gid")->find();
//        dd($goodsData);
        $this->assign("goodsData",$goodsData);
        // 获取商品规格数据
        $data = M("tproperty")->alias("tp")->join("xm_goods_attr ga on tp.tpid = ga.tpid")->where("gid={$gid} and tptype=2")->field("tp.tpid,tpname,gaid,gattr")->select();
        $arr = [];
        foreach($data as $k => $v){
            $arr[$v['tpname']]["name"] = $v['tpname'];
            $arr[$v['tpname']]["value"][] = $v;
        }
//        dd($arr);
        $this->assign("arr",$arr);
        $this->display();
    }

    public function getGlinventory(){
        if(IS_AJAX){
            $gid = I("post.gid");
            $groupid = rtrim(I("post.groupid"),"|");
            $inventory = M("GoodsList")->where("gid=$gid and groupid='$groupid'")->getField("glinventory");
            if(!$inventory || $inventory == 0){
                $this->ajaxReturn(['valid'=>false,'inventory'=>0]);exit;
            }
            $this->ajaxReturn(['valid'=>true,'inventory'=>$inventory]);exit;
        }
    }

    public function addCart(){
        if(IS_AJAX){
            $gid = I("post.gid");
            $goods = M("Goods")->where("gid=$gid")->find();
            $options = I("post.gattr");

            $data = [
                'id'        => $gid, // 商品 ID
                'name'      =>$goods['gname'],// 商品名称
                'num'       => 1, // 商品数量
                'price'     => $goods['xmprice'], // 商品价格
                'options'   => $options// 其他参数如价格、颜色、可以为数组或字符串
            ];
            (new Cart())->add($data); // 添加到购物车
//            dd($_SESSION);
            echo 1;exit;
        }
    }
}